# -*- coding:utf-8 -*-
# @Time : 2020/9/21 20:52
# @Author : liruiyang
# @File : UserInfoModel
# @Software: PyCharm
# @Description: 这是一个python程序
# here put the import lib
import datetime

from flask import current_app

from .. import db
from werkzeug.security import generate_password_hash, check_password_hash

from ..utils import commons
from ..utils.response_code import RET


class AdminInfo(db.Model):
    __tablename__ = 'admin_info'

    UserID = db.Column(db.String(20), primary_key=True, nullable=False)
    UserName = db.Column(db.String(255, 'utf8mb4_0900_ai_ci'), nullable=False)
    Mail = db.Column(db.String(255), primary_key=True, nullable=False)
    Password = db.Column(db.String(255, 'utf8mb4_0900_ai_ci'), nullable=False)
    OtherInfo = db.Column(db.String(255, 'utf8mb4_0900_ai_ci'), nullable=False)

    @classmethod
    def get_user(cls, user_id):
        '''
        给flask-login调用的方法
        :param user_id: 用户id
        :return:
        '''
        filter_list = []
        filter_list.append(cls.UserID == user_id)

        try:
            student = db.session.query(cls).filter(*filter_list)
        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取用户信息失败', 'error': str(e)}

        if not student.first():
            return {'code': RET.NODATA, 'message': '无用户信息', 'error': '无用户信息'}

        # 处理返回的数据
        return {'code': RET.OK, 'message': 'OK', 'data': student.first()}

    @classmethod
    def check_password(cls, **kwargs):
        old_password = kwargs.get('Password')

        try:
            filter_list = []
            if kwargs.get('UserID'):
                filter_list.append(cls.UserID == kwargs.get('UserID'))
            if kwargs.get('Mail'):
                filter_list.append(cls.Mail == kwargs.get('Mail'))

            user = db.session.query(cls).filter(*filter_list).first()

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取学生信息失败', 'error': str(e)}

        if not user:
            return {'code': RET.NODATA, 'message': '无用户信息', 'error': '无用户信息'}

        if not check_password_hash(user.Password, old_password):
            return {'code': RET.PWDERR, 'message': '用户名或密码错误', 'error': '用户名或密码错误'}

        return {'code': RET.OK, 'message': '密码正确', 'data': commons.query_to_dict(user)}

    @classmethod
    def add_user(cls, **kwargs):
        user_name = kwargs.get('UserName')
        mail = kwargs.get('Mail')
        password = kwargs.get('Password') if kwargs.get('Password') else '123456'

        # 检查是否有重复的邮箱
        try:
            filter_list = []
            filter_list.append(cls.Mail == mail)

            MailModel = db.session.query(cls).filter(*filter_list)

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，获取信息失败', 'error': str(e)}

        if MailModel.first():
            return {'code': RET.DATAEXIST, 'message': '账号邮箱已存在', 'error': "账号邮箱已存在"}

        # 生成用户id 插入信息到表里
        try:
            user_id = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
            Admin = AdminInfo(
                UserID=user_id,
                UserName=user_name,
                Password=generate_password_hash(password),
                OtherInfo=kwargs.get('OtherInfo'),
                Mail=mail,
            )
            db.session.add(Admin)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，添加用户账号失败', 'error': str(e)}

        data = commons.query_to_dict(Admin)
        back_data = {
            'UserID': data.get('UserID'),
            'CreateTime': data.get('CreateTime')
        }

        return {'code': RET.OK, 'message': '创建用户账户成功', 'data': back_data}

    @classmethod
    def reset_password(cls, **kwargs):
        new_password = kwargs.get('Password') if kwargs.get('Password') else '123456'

        try:
            filter_list = []
            filter_list.append(cls.UserID == kwargs.get('UserID'))

            user = db.session.query(cls).filter(*filter_list)

        except Exception as e:
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，查询用户信息失败', 'error': str(e)}

        if not user.first():
            return {'code': RET.NODATA, 'message': '无用户信息', 'error': '无用户信息'}

        try:
            user.update({
                'Password': generate_password_hash(new_password)
            })
            db.session.commit()

        except Exception as e:
            db.session.rollback()
            current_app.logger.error(e)
            return {'code': RET.DBERR, 'message': '数据库异常，重置用户密码失败', 'error': str(e)}

        data = commons.query_to_dict(user.first())

        back_data = {
            'UserID': data.get('UserID'),
            'NewPassword': data.get('Password')
        }

        return {'code': RET.OK, 'message': '重置密码成功', 'data': back_data}
